//
//  CustomFloatingButton.swift
//  Sample
//
//  Created by Ranki on 2025/7/12.
//  Copyright © 2025 Roy Marmelstein. All rights reserved.
//

import UIKit

// MARK: - 定义回调协议
protocol CustomFloatingButtonDelegate: AnyObject {
    func floatingButtonDidTapTranslate()
    func floatingButtonDidTapTranslating()
}

// MARK: - 定义回调闭包类型
typealias TranslateCallback = () -> Void
typealias TranslatingCallback = () -> Void

class CustomFloatingButton: UIView {
    
    // MARK: - Singleton
    static let shared = CustomFloatingButton()
    
    // MARK: - Properties
    private let titleLabel = UILabel()
    private var isTranslating = false
    
    // MARK: - 回调属性
    weak var delegate: CustomFloatingButtonDelegate?
    var onTranslateTap: TranslateCallback?
    var onTranslatingTap: TranslatingCallback?
    
    // MARK: - Initialization
    private override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        // 设置背景
        backgroundColor = .systemBlue
        layer.cornerRadius = 25
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 2)
        layer.shadowOpacity = 0.3
        layer.shadowRadius = 4
        
        // 设置标题标签
        titleLabel.text = "翻译"
        titleLabel.textColor = .white
        titleLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        titleLabel.textAlignment = .center
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        addSubview(titleLabel)
        
        // 设置约束
        NSLayoutConstraint.activate([
            titleLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
            titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
            titleLabel.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor, constant: 8),
            titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: -8)
        ])
        
        // 添加拖拽手势
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
        addGestureRecognizer(panGesture)
        
        // 添加点击手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        addGestureRecognizer(tapGesture)
    }
    
    // MARK: - Gesture Handlers
    @objc private func handlePan(_ gesture: UIPanGestureRecognizer) {
        let translation = gesture.translation(in: superview)
        
        switch gesture.state {
        case .changed:
            center = CGPoint(x: center.x + translation.x, y: center.y + translation.y)
            gesture.setTranslation(.zero, in: superview)
        case .ended:
            snapToEdge()
        default:
            break
        }
    }
    
    @objc private func handleTap() {
        // 切换翻译状态
        isTranslating.toggle()
        
        // 更新文案和样式
        updateAppearance()
        
        // 触发回调事件
        triggerCallback()
    }
    
    // MARK: - UI Updates
    private func updateAppearance() {
        UIView.animate(withDuration: 0.3) {
            if self.isTranslating {
                // 翻译中状态
                self.titleLabel.text = "翻译中"
                self.backgroundColor = .systemOrange
                self.titleLabel.textColor = .white
            } else {
                // 翻译状态
                self.titleLabel.text = "翻译"
                self.backgroundColor = .systemBlue
                self.titleLabel.textColor = .white
            }
        }
    }
    
    // MARK: - Callback Handling
    private func triggerCallback() {
        if isTranslating {
            // 触发翻译中事件
            delegate?.floatingButtonDidTapTranslating()
            onTranslatingTap?()
        } else {
            // 触发翻译事件
            delegate?.floatingButtonDidTapTranslate()
            onTranslateTap?()
        }
    }
    
    // MARK: - Edge Snapping
    private func snapToEdge() {
        guard let superview = superview else { return }
        
        let screenWidth = superview.bounds.width
        let screenHeight = superview.bounds.height
        let centerX = center.x
        let centerY = center.y
        
        // 计算目标位置
        let targetX: CGFloat
        let targetY: CGFloat
        
        // 水平吸附
        if centerX < screenWidth / 2 {
            targetX = 30
        } else {
            targetX = screenWidth - 30
        }
        
        // 垂直限制（确保不超出屏幕）
        targetY = max(50, min(screenHeight - 50, centerY))
        
        UIView.animate(withDuration: 0.3) {
            self.center = CGPoint(x: targetX, y: targetY)
        }
    }
    
    // MARK: - Public Methods
    func setTranslating(_ translating: Bool) {
        isTranslating = translating
        updateAppearance()
    }
    
    func getTranslationState() -> Bool {
        return isTranslating
    }
    
    // MARK: - Singleton Methods
    static func setup(delegate: CustomFloatingButtonDelegate? = nil,
                     onTranslateTap: TranslateCallback? = nil,
                     onTranslatingTap: TranslatingCallback? = nil) {
        shared.delegate = delegate
        shared.onTranslateTap = onTranslateTap
        shared.onTranslatingTap = onTranslatingTap
    }
    
    static func show(in view: UIView, frame: CGRect = CGRect(x: 0, y: 100, width: 80, height: 50)) {
        shared.frame = frame
        if shared.superview == nil {
            view.addSubview(shared)
        }
    }
    
    static func showInWindow(frame: CGRect = CGRect(x: 0, y: 100, width: 80, height: 50)) {
        if let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) {
            show(in: window, frame: frame)
        }
    }
    
    static func hide() {
        shared.removeFromSuperview()
    }
    
    // MARK: - Window Level Management
    static func bringToFront() {
        if let superview = shared.superview {
            superview.bringSubviewToFront(shared)
        }
    }
    
    static func setWindowLevel(_ level: UIWindow.Level) {
        if let window = shared.superview as? UIWindow {
            window.windowLevel = level
        }
    }
}
